package com.lkd.intercept;

import com.lkd.utils.UserThreadLocal;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author brianxia
 * @version 1.0
 * @date 2023-02-07 16:06
 */
public class UserInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String userId = request.getHeader("userId");
        if(StringUtils.isNotBlank(userId)){
            //放入threadLocal
            UserThreadLocal.userId.set(Integer.valueOf(userId));
        }
        //false后边controller不会执行
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清理
        UserThreadLocal.userId.remove();
    }
}
